//
//  PostActivityTableViewController.m
//  app001
//
//  Created by xionghao on 15/10/9.
//  Copyright © 2015年 xionghao. All rights reserved.
//

#import "PostActivityTableViewController.h"
#import "Pubmode.h"
#import "LongPeizhi.h"
#import "AddBtnMode.h"
#import "ContentMode.h"
#import "TitleModel.h"
#import "AddCarPeizhiTableViewCell.h"
#import "AddBtnTableViewCell.h"
#import "PublishTopTableViewCell.h"
#import "NomralAddTitleTableViewCell.h"
#import "JianjieViewController.h"
#import "ZTActivityORGETPICCell.h"
#import "LCActionSheet.h"
#import "UploadParams.h"
#import "UserInfoUpdateResde.h"
#import "ZTListContent.h"
#import "ZTActivityModel.h"
#import "ZTActivityPostSUSViewController.h"
#import "ZTSelectCarController.h"
#import "ZCModel.h"


@interface PostActivityTableViewController ()<addClickDelegate,LCActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ADActivityORGetCellDelegate,ZTSelectCarControllerDelegate>

@property (nonatomic,strong) NSMutableArray *datalist;
@property (nonatomic,strong) NSMutableArray *contentlist;
@property (nonatomic,strong) UIImagePickerController *picker;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) Pubmode *titlemode;
@property (nonatomic,strong) LongPeizhi *content;

@end

@implementation PostActivityTableViewController
+(instancetype)viewcontroller{
    PostActivityTableViewController *vc=[[PostActivityTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    return vc;
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}


-(NSMutableArray *)datalist{
    if ( _datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return  _datalist;
}
-(void)addbtnclick{
    
    NSArray *titlearray;
    if (self.isActivtiy) {
        titlearray=@[@"从相册中选择",@"选择展车链接"];
        
    }else{
        titlearray=@[@"从相册中选择",@"拍照"];
    }
    
    LCActionSheet *sheet=[[LCActionSheet alloc] initWithTitle:nil buttonTitles:titlearray redButtonIndex:-1 delegate:self];
    [sheet show];
    //    ContentMode *mode =[[ContentMode alloc] init];
    //    mode.rowheight=100;
    //    [self.contentlist insertObject:mode atIndex:self.contentlist.count-1];
    //   NSIndexSet *set= [NSIndexSet indexSetWithIndex:2];
    //    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(void)cell:(ZTActivityORGETPICCell *)cell clickWithIndex:(NSInteger)index{
    NSIndexPath *indexpath=[self.tableView indexPathForCell:cell];
    if (index==0) {
        [self.contentlist removeObjectAtIndex:indexpath.row];
        [self reloadsection:2];
    }else{
        JianjieViewController *vc=[JianjieViewController viewcontroller];
        vc.navtitle=self.isActivtiy?@"活动内容":@"纪念内容";
        ContentMode *mode=self.contentlist[indexpath.row];
        vc.text=mode.info;
        vc.textlength=100;
        vc.block=^(NSString *string){
            mode.info=string;
            [self.tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor whiteColor];
        
        _picker.delegate =self;
        
    }
    return _picker;
}
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==2) {
        return;
    }else{
        if (buttonIndex==0) {
            UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypePhotoLibrary;
            self.picker.sourceType=sourcheType;
            [self presentViewController:self.picker animated:YES completion:nil];
        }else{
            if (self.isActivtiy) {
                [self pustoZTSELET];
            }else{
                UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
                self.picker.sourceType=sourcheType;
                [self presentViewController:self.picker animated:YES completion:nil];
            }
            
        }
        
    }
}

-(void)pustoZTSELET{
    ZTSelectCarController *svc=[[ZTSelectCarController alloc] init];
    svc.delegate=self;
    [self.navigationController pushViewController:svc animated:YES];
}




-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        ContentMode *mode=[[ContentMode alloc]init];
        mode.rowheight=100;
        mode.image=image;
        mode.isChange=YES;
        [self.contentlist insertObject:mode atIndex:self.contentlist.count-1];
        [self reloadsection:2];
        [self tableViewScrollToBottom];
    }];
    
}
-(void)SelectedCarList:(NSArray *)array{
    for (ZCModel *mode in array) {
        ContentMode *cmode=[[ContentMode alloc]init];
        cmode.rowheight=100;
        cmode.ID=mode.ID;
        cmode.url=mode.pic==nil||[mode.pic isEqualToString:@""]?mode.brand_logo:mode.pic;
        cmode.isChange=YES;
        [self.contentlist insertObject:cmode atIndex:self.contentlist.count-1];
       
    }
    [self reloadsection:2];
    [self tableViewScrollToBottom];
}

-(void)reloadsection:(NSInteger)index{
    NSIndexSet *set= [NSIndexSet indexSetWithIndex:index];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(NSMutableArray *)contentlist{
    if ( _contentlist==nil) {
        _contentlist=[NSMutableArray array];
    }
    return  _contentlist;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self removeSUS];
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 64, 0);
    self.navigationItem.title=self.isActivtiy?@"发布活动":@"发布纪念";
    self.tableView.backgroundColor=bgGarycolor;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    [self setupdata];
    [self setupbtn];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)removeSUS{
    NSMutableArray *marray=[NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[ZTActivityPostSUSViewController class]]) {
            [marray removeObject:vc];
        }
    }
    self.navigationController.viewControllers=marray;
}

- (void)tableViewScrollToBottom
{
    
    NSArray *array=self.datalist[2];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:array.count-1 inSection:2];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}



- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}

-(void)setupbtn{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, XHScreenwidth, 60)];
    UIButton *postbtn=[[UIButton alloc] initWithFrame:CGRectMake(16, 24, XHScreenwidth-32, 36)];
    
    if (self.mode) {
         [postbtn setTitle:self.isActivtiy?@"修改活动":@"修改纪念" forState:UIControlStateNormal];
    }else{
    [postbtn setTitle:self.isActivtiy?@"立即发布":@"立即添加" forState:UIControlStateNormal];
    }
    [postbtn setBackgroundImage:[UIImage imageWithStretchableName:@"button_zc"] forState:UIControlStateNormal];
    [postbtn addTarget:self action:@selector(postclick) forControlEvents:UIControlEventTouchUpInside];
    [postbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [view addSubview:postbtn];
    self.tableView.tableFooterView=view;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)postclick{
    if ( [self checkform]) {
        
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在发布...";
       
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        
        NSInteger power=[self.user.power integerValue];
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"title"]=self.titlemode.detail;
        params[@"msg"]=self.content.loogdetail;
        params[@"user_id"]=power<5?self.user.user_id:self.user.com_id;
        params[@"type"]=power<5?@"person":@"company";
        if (power==8) {
            params[@"pid"]=self.user.parent_id;
        }
        
        NSMutableArray *marray=[NSMutableArray array];
        for (Pubmode *mode in self.contentlist) {
            if ([mode isKindOfClass:[ContentMode class]]) {
                ContentMode *cmode=mode;
                NSMutableDictionary *mdict=[NSMutableDictionary dictionary];
                if (cmode.ID&&self.isActivtiy) {
                   
                    mdict[@"id"]=cmode.ID;
                }else{
                    if (self.isActivtiy) {
                        mdict[@"id"]=@"0";
                    }
                if (cmode.isChange) {
                    NSData *imagedata=[UIImage compressData:cmode.image toMaxFileSize:DefailutPicSize];
                    NSString *base64str=[imagedata imageBase64Data:imagedata];
                    mdict[@"pic"]=base64str;
                }else{
                    mdict[@"pic"]=cmode.url;
                }
                }
                mdict[@"msg"]=cmode.info;
                [marray addObject:mdict];
            }
        }
        if (marray.count>0) {
            params[@"content"]=[NSString DataTOjsonString:marray];
            //                NSLog(@"%@",[NSString DataTOjsonString:marray]);
            
        }

        
        if (self.isActivtiy) {
            
           
            if (self.mode) {
                params[@"id"]=self.mode.ID;
                params[@"action"]=@"edit_act";
            }else{
                params[@"action"]=@"add_act";
            }

            
        }else{
            
            if (self.mode) {
                params[@"id"]=self.mode.ID;
                params[@"action"]=@"edit_jn";
            }else{
            params[@"action"]=@"add_jn";
            }
           
            
        }
        [PostUitls Post:mynewzturl parameters:params success:^(id response) {
            UserInfoUpdateResde *resdemode=[UserInfoUpdateResde resdeWithDict:response];
            hud.mode=MBProgressHUDModeText;
            hud.labelText=resdemode.msg;
            
            if ([resdemode.state integerValue]==400) {
                ZTActivityPostSUSViewController *vc=[[ZTActivityPostSUSViewController alloc]init];
                vc.isActiviy=self.isActivtiy;
                if (self.mode) {
                    vc.ID=self.mode.ID;
                }else{
                vc.ID=resdemode.data;
                }
                [self.navigationController pushViewController:vc animated:YES];
            }
            [hud hide:YES afterDelay:1];
        } failure:^(NSError *error) {
            hud.mode=MBProgressHUDModeText;
            hud.labelText=NetWorkError;
            [hud hide:YES afterDelay:1];
        }];

    }
    
}
-(BOOL)checkform{
    return YES;
}
-(void)setupdata{
    
    
    
    
    Pubmode *title=[[Pubmode alloc] init];
    title.name=self.isActivtiy?@"活动主题":@"纪念主题";
    title.detail=@"";
    
    if (self.mode) {
        title.detail=self.mode.title;
    }else{
        title.detail=@"";
    }
    title.block=^{
        JianjieViewController *vc=[JianjieViewController viewcontroller];
        vc.navtitle=title.name;
        vc.text=title.detail;
        vc.block=^(NSString *str){
            title.detail=str;
            NSIndexSet *set=[NSIndexSet indexSetWithIndex:0];
            [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        [self.navigationController pushViewController:vc animated:YES];
    };
     self.titlemode=title;
    
    LongPeizhi *content=[[LongPeizhi alloc] init];
    content.name=self.isActivtiy?@"活动介绍":@"纪念介绍";
    if (self.mode) {
        content.loogdetail=self.mode.msg;
    }
    
    self.content=content;
    content.block=^{
        JianjieViewController *vc=[JianjieViewController viewcontroller];
        vc.navtitle=content.name;
        vc.text=content.loogdetail;
        vc.block=^(NSString *str){
            content.loogdetail=str;
            NSIndexSet *set=[NSIndexSet indexSetWithIndex:1];
            [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    
    TitleModel *imgtitle=[[TitleModel alloc] init];
    imgtitle.name=self.isActivtiy?@"添加图片/链接":@"添加图片";
    AddBtnMode *addbtn=[[AddBtnMode alloc]init];
    addbtn.rowheight=80;
    [self.contentlist addObject:imgtitle];
    if (self.mode) {
        for (ZTListContent *listcontent in self.mode.content) {
            ContentMode *cmode=[[ContentMode alloc] init
                                ];
            cmode.info=listcontent.msg;
            cmode.url=listcontent.pic;
            cmode.rowheight=100;
            [self.contentlist addObject:cmode];
        }
    }
    
    [self.contentlist addObject:addbtn];
    
    
    [self.datalist addObject:@[title]];
    [self.datalist addObject:@[content]];
    [self.datalist addObject:self.contentlist];
    
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 16;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return self.datalist.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    
    NSArray *array=self.datalist[section];
    
    return array.count;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.datalist[indexPath.section];
    Pubmode *mode=array[indexPath.row];
    
    if (mode.block) {
        mode.block();
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *array=self.datalist[indexPath.section];
    Pubmode *mode=array[indexPath.row];
    if ([mode isKindOfClass:[LongPeizhi class]]) {
        LongPeizhi *peizhi=mode;
        AddCarPeizhiTableViewCell *cell=[AddCarPeizhiTableViewCell cellWithTableView:tableView];
        
        cell.peizhi=peizhi;
        
        return cell;
    }else if ([mode isKindOfClass:[AddBtnMode class]]){
        AddBtnTableViewCell *cell=[AddBtnTableViewCell cellWithTableView:tableView];
        cell.delegate=self;
        return cell;
    }else if ([mode isKindOfClass:[TitleModel class]]){
        NomralAddTitleTableViewCell *cell=[NomralAddTitleTableViewCell cellWithTableView:tableView];
        cell.titlelable.text=mode.name;
        return cell;
    }else if ([mode isKindOfClass:[ContentMode class]]){
        ZTActivityORGETPICCell *cell=[ZTActivityORGETPICCell cellWithTableView:tableView];
        cell.mode=mode;
        cell.delegate=self;
        return cell;
        
    }
    else{
        PublishTopTableViewCell *cell=[PublishTopTableViewCell cellWithTableView:tableView];
        cell.mode=mode;
        if ([mode.detail isEqualToString:@""]) {
            cell.detail.text=@"";
            
        }
        cell.detail.textColor=textnormalGary;
        return cell;
    }
    
    
    
    // Configure the cell
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.datalist[indexPath.section];
    Pubmode *mode=array[indexPath.row];
    if (mode.rowheight) {
        return mode.rowheight;
    }else{
        return 44;
    }
    
}




@end
